package com.eshipenet.shipnet.equipmentextbuilder

import org.joda.time.DateTime
import play.api.libs.json._

import scala.languageFeature.postfixOps

object EquipmentExtActionSerializer {

  def apply(action: EquipmentExtAction, timestamp: Option[DateTime] = None): List[(String, JsValue)] = action match {
    case EquipmentExtInsert(after) =>
      val models = JsArray(after.models.values.map(_.raw).toSeq)
      val value = Json.obj(
        "schema" -> Json.obj(),
        "payload" -> Json.obj(
          "op"     -> "i",
          "after"  -> after.equipment.raw.+("models" -> models),
          "source" -> Json.obj(),
          "ts_ms"  -> timestamp.getOrElse(DateTime.now()).getMillis,
        )
      )
      val key = action.id
      List((key, value))

    case EquipmentExtUpdate(before, after) =>
      val models = JsArray(after.models.values.map(_.raw).toSeq)
      val value = Json.obj(
        "schema" -> Json.obj(),
        "payload" -> Json.obj(
          "op"     -> "u",
          "before" -> before.equipment.raw.+("models" -> models),
          "after"  -> after.equipment.raw + "models" -> after.models.values.map(_.raw),
          "source" -> Json.obj(),
          "ts_ms"  -> timestamp.getOrElse(DateTime.now()).getMillis,
        )
      )
      val key = action.id
      List((key, value))
    case EquipmentExtDelete(before) =>
      val models = JsArray(before.models.values.map(_.raw).toSeq)
      val value = Json.obj(
        "schema" -> Json.obj(),
        "payload" -> Json.obj(
          "op"     -> "i",
          "before" -> before.equipment.raw.+("models" -> models),
          "source" -> Json.obj(),
          "ts_ms"  -> timestamp.getOrElse(DateTime.now()).getMillis,
        )
      )
      val key = action.id
      List((key, value), (key, JsNull))
  }

}
